package member.base.action;

import m.common.action.ActionRequest;
import m.common.action.Param;
import m.common.action.RequestMethod;
import m.common.model.util.*;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;
import member.base.model.UserInfo;
import member.base.service.UserInfoService;
import member.base.util.PowerUtil;

import java.util.Arrays;

@ActionRequest(name = "action/base/userInfo",description = "用户")
public class UserInfoAction extends BaseAction {
    private final UserInfoService service=getService(UserInfoService.class);

    @RequestMethod(description = "用户登录")
    public JSONMessage login(@Param("model") UserInfo model) throws Exception {
        ModelQueryCheck.init(model)
            .checkNotNull("phoneNum","手机号不能为空")
            .checkNotNull("password","密码不能为空")
            .doCheck(false,true);
        UserInfo user=service.getUserByLogin(model.getPhoneNum(), StringUtil.to32MD5(model.getPassword()));
        if(null==user) throw new MException("手机号或密码错误");
        user.setToken(GenerateID.generatePrimaryKey()+GenerateID.upsetKey(GenerateID.generatePrimaryKey()));
        ModelUpdateUtil.updateModel(user,"token");
        PowerUtil.setUser(user.getOid());
        return JSONMessage.success("登录成功")
            .push("user",user);
    }
    @RequestMethod(description = "退出登录")
    public JSONMessage logout() throws MException {
        String userOid=PowerUtil.clearUser();
        if(StringUtil.notSpace(userOid)) {
            UserInfo user = new UserInfo();
            user.setOid(userOid);
            user.setToken("");
            ModelUpdateUtil.updateModel(user, "token");
        }
        return JSONMessage.success("退出登录成功");
    }
    @RequestMethod(description = "保存用户常用菜单")
    public JSONMessage saveMenus(@Param("menus") String[] menus) throws Exception {
        if(null==menus||menus.length<3) throw new MException("设置错误");
        UserInfo user=PowerUtil.getUser();
        user.setMenus(menus);
        ModelUpdateUtil.updateModel(user,"menus");
        return JSONMessage.success("保存成功");
    }
    @RequestMethod(description = "列表")
    public JSONMessage getList() throws Exception {
        ModelQueryList queryList=toQueryList(UserInfo.class,"*","store.*","store.user.realName");
        queryList.addCondition(QueryCondition.eq("business.oid", PowerUtil.getBusiness().getOid()));
        queryList.addFieldExpression("password","''");
        return JSONMessage.success("查询成功").push("page",ModelQueryList.getModelPageInfo(queryList));
    }
    @RequestMethod(description = "保存密码")
    public JSONMessage savePassword(@Param("oldPassword") String oldPassword,@Param("newPassword") String newPassword) throws Exception {
        if(StringUtil.isSpace(oldPassword)) throw new MException("请输入原密码");
        if(StringUtil.isSpace(newPassword)) throw new MException("请输入新密码");
        UserInfo user;
        try {
            user = service.getUserByLogin(PowerUtil.getUser().getPhoneNum(), StringUtil.to32MD5(oldPassword));
        }catch (Exception e){
            throw new MException("原密码错误");
        }
        user.setPassword(StringUtil.to32MD5(newPassword));
        ModelUpdateUtil.updateModel(user,"password");
        return JSONMessage.success("修改成功");
    }
    @RequestMethod(description = "保存")
    public JSONMessage save(@Param("model") UserInfo model) throws Exception {
        PowerUtil.verifyPower(UserInfo.PowerManage);
        model.setBusiness(PowerUtil.verifyBusiness(model.getBusiness()));
        if(ObjectUtil.notEmptyOid(model)&&model.getBusiness().getUser().getOid().equals(model.getOid())
            &&!Arrays.asList(model.getPowers()).contains(UserInfo.PowerManage)){
            throw new MException("店铺创建人必须保留管理权限");
        }
        ModelQueryCheck.init(model)
            .checkNotNull("realName","姓名不能为空")
            .checkNotNull("phoneNum","手机号不能为空")
            .checkNotNull("store.oid","店铺不能为空")
            .doCheck(false,true);
        ModelCheckUtil.checkUniqueCombine(model,new String[]{"business.oid","realName"},"姓名已存在");
        ModelCheckUtil.checkUniqueCombine(model,new String[]{"phoneNum"},"手机号已存在");
        if(StringUtil.notSpace(model.getPassword())){
            model.setPassword(StringUtil.to32MD5(model.getPassword()));
            ModelUpdateUtil.saveModel(model,"realName","phoneNum","store.oid","powers","status","wages","orderRatio","rechargeRatio","password");
        }else {
            if(ObjectUtil.isEmptyOid(model)&&StringUtil.isSpace(model.getPassword()))
                throw new MException("密码不能为空");
            ModelUpdateUtil.saveModel(model,"realName","phoneNum","store.oid","powers","status","wages","orderRatio","rechargeRatio");
        }
        PowerUtil.resetUser(model.getOid());
        return JSONMessage.success("保存成功");
    }
}
